import {
  registerMicroApps,
  start,
  addGlobalUncaughtErrorHandler,
} from "qiankun";
import setting from "@/settings";
export { qiankunActions } from "./globalState";
import { initialState } from "./globalState";
import store from "@/store";
import { Loading, Message } from "element-ui";

import router from "@/router";
let loadFull;
/* qiankun全局声明周期钩子 */
const microConfig = {
  beforeLoad: [
    (app) => {
      console.log(
        "%c before load",
        "background:#3a5ab0 ; padding: 1px; border-radius: 3px;  color: #fff",
        app
      );
    },
  ], // 预加载
  beforeMount: [
    (app) => {
      console.log(
        "%c before mount",
        "background:#7d9553 ; padding: 1px; border-radius: 3px;  color: #fff",
        app
      );
    },
  ], // 挂载前回调
  afterMount: [
    (app) => {
      console.log(
        "%c after mount",
        "background:#7d7453 ; padding: 1px; border-radius: 3px;  color: #fff",
        app
      );
    },
  ], // 挂载后回调
  beforeUnmount: [
    (app) => {
      console.log(
        "%c before unmount",
        "background:#7dd253 ; padding: 1px; border-radius: 3px;  color: #fff",
        app
      );
    },
  ], // 卸载前回调
  afterUnmount: [
    (app) => {
      console.log(
        "%c after unmount",
        "background:#d2525c ; padding: 1px; border-radius: 3px;  color: #fff",
        app
      );
    },
  ], // 卸载后回调
};

// 微应用注册
export const registerApps = (router, $tab) => {
  registerMicroApps(
    setting.microApps.map((item) => {
      return {
        ...item,
        entry:
          process.env === "production"
            ? `${item.entry}`
            : `${item.entry}modules/${item.name}/`,
        props: {
          routerBase: item.activeRule, // 下发基础路由
          globalState: initialState, // 下发全局数据方法
          store,
          router,
          $tab,
          setting,
        },
        container: "#subApp-viewport",
        loader: (loading, next) => {
          // console.error("loading", next, loading, new Date().getTime());
          // if (loading) {
          //   loadFull = Loading.service({
          //     fullscreen: true,
          //     body: true,
          //     lock: true,
          //     text: "",
          //     spinner: "el-icon-loading",
          //     background: "rgba(255,255,255,.16)",
          //     customClass: "body-loading",
          //   });
          // } else {
          //   setTimeout(() => {
          //     loadFull.close();
          //   }, 550);
          // }
        },
      };
    }),
    microConfig
  );
  start({
    prefetch: "all", // 可选，是否开启预加载，默认为 true。
    sandbox: { strictStyleIsolation: false }, // 可选，是否开启沙箱，默认为 true。// 从而确保微应用的样式不会对全局造成影响。
    singular: true, // 可选，是否为单实例场景，单实例指的是同一时间只会渲染一个微应用。默认为 true。
  });
  // setDefaultMountApp("/modules/sub");
};
addGlobalUncaughtErrorHandler((e) => {
  loadFull && loadFull.close();
  if (e.type == "error") {
    // Message.warning("页面不存在！");
    // router.replace("/index");
  }
});
